package com.woniuxy.charin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.charin.model.entity.ActivityInfo;
import com.woniuxy.charin.model.entity.Station;

import com.woniuxy.charin.model.vo.ActivityInfoVo;
import com.woniuxy.charin.model.vo.PageResponse;
import com.woniuxy.charin.service.ActivityInfoService;
import com.woniuxy.charin.service.StationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/activityInfo")
@Api(tags = "活动管理")
@Slf4j
public class ActivityInfoController {

    @Autowired
    private ActivityInfoService activityInfoService;

    @Autowired
    private StationService stationService;


    // 获取活动关联的站点
    @GetMapping("/getActivityStations")
    @ApiOperation("获取活动关联的站点")
    public ResponseEntity<List<Station>> getActivityStations(@RequestParam Long activityId) {
        log.info("getActivityStations - activityId: {}", activityId);
        try {
            List<Station> stations = activityInfoService.getActivityStations(activityId);
            return ResponseEntity.ok(stations);
        } catch (Exception e) {
            log.error("获取活动关联站点失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    @GetMapping("/detail/{id}")
    @ApiOperation("获取活动详细信息")
    public ResponseEntity<Map<String, Object>> getActivityDetail(@PathVariable int id) {
        log.info("getActivityDetail - id: {}", id);

        ActivityInfo activityInfo = activityInfoService.getById(id);
        if (activityInfo == null) {
            return ResponseEntity.notFound().build();
        }

        // 使用现有的 getStationList 方法获取相关站点
        PageResponse<Station> stationResponse = stationService.getStationList(
                null,           // stationName
                "正常",         // status - 只获取正常状态的站点
                null,           // address
                1,             // page
                Integer.MAX_VALUE  // size - 获取所有记录
        );

        Map<String, Object> result = new HashMap<>();
        result.put("activity", activityInfo);
        result.put("stations", stationResponse.getRecords());

        return ResponseEntity.ok(result);
    }


    // 添加活动关联站点
    @PostMapping("/addActivityStations")
    @ApiOperation("添加活动关联站点")
    public ResponseEntity<String> addActivityStations(
            @RequestParam Long activityId,
            @RequestParam List<Long> stationIds) {
        log.info("addActivityStations - activityId: {}, stationIds: {}", activityId, stationIds);
        try {
            boolean success = activityInfoService.addActivityStations(activityId, stationIds);
            return ResponseEntity.ok(success ? "站点关联成功" : "站点关联失败");
        } catch (Exception e) {
            log.error("添加活动关联站点失败", e);
            return ResponseEntity.badRequest().body("添加活动关联站点失败");
        }
    }
    // 修改添加活动的接口，返回活动ID
    @PostMapping("/add")
    @ApiOperation("添加活动信息")
    public ResponseEntity<Long> add(@RequestBody ActivityInfo activityInfo) {
        log.info("add - activityInfo: {}", activityInfo);
        try {
            boolean saved = activityInfoService.save(activityInfo);
            if (saved) {
                return ResponseEntity.ok(activityInfo.getId());
            } else {
                return ResponseEntity.badRequest().build();
            }
        } catch (Exception e) {
            log.error("添加活动失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    @GetMapping("/getAvailableStations")
    @ApiOperation("获取可选择的站点列表")
    public ResponseEntity<List<Station>> getAvailableStations(
            @RequestParam(required = false) String stationName,
            @RequestParam(required = false) String stationType) {
        log.info("getAvailableStations - stationName: {}, stationType: {}", stationName, stationType);

        // 构建查询条件
        QueryWrapper<Station> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(stationName)) {
            queryWrapper.lambda().like(Station::getStationName, stationName);
        }
        if (StringUtils.isNotBlank(stationType)) {
            queryWrapper.lambda().eq(Station::getStationType, stationType);
        }
        // 只查询状态正常的站点
        queryWrapper.lambda().eq(Station::getStatus, "正常");

        List<Station> stations = stationService.list(queryWrapper);
        return ResponseEntity.ok(stations);
    }
    @GetMapping("/list")
    @ApiOperation("分页查询活动信息")
    public ResponseEntity<Page<ActivityInfoVo>> list(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String activityName,
            @RequestParam(required = false) String status) {

        log.info("list - current: {}, size: {}, activityName: {}, status: {}", current, size, activityName, status);

        QueryWrapper<ActivityInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(activityName)) {
            queryWrapper.lambda().like(ActivityInfo::getActivityName, activityName);
        }
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.lambda().eq(ActivityInfo::getStatus, status);
        }

        // 按创建时间倒序排序
        queryWrapper.orderByDesc("creation_time");

        Page<ActivityInfo> entityPage = activityInfoService.page(new Page<>(current, size), queryWrapper);
        // 转换为VO对象
        Page<ActivityInfoVo> voPage = new Page<>(current, size, entityPage.getTotal());
        List<ActivityInfoVo> voList = entityPage.getRecords().stream()
                .map(entity -> {
                    ActivityInfoVo vo = new ActivityInfoVo();
                    BeanUtils.copyProperties(entity, vo);  // 这里会复制所有匹配的字段

                    // 设置默认值
                    if (StringUtils.isBlank(vo.getStationName())) {
                        vo.setStationName("暂无站点信息");
                    }
                    if (StringUtils.isBlank(vo.getStationAddress())) {
                        vo.setStationAddress("暂无地址信息");
                    }

                    // 可以在这里添加日志来检查数据转换是否正确
                    log.debug("Converting entity to VO: entity={}, vo={}", entity, vo);

                    return vo;
                })
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return ResponseEntity.ok(voPage);
    }


    @DeleteMapping("/delete")
    @ApiOperation("删除活动信息")
    public ResponseEntity<String> delete(@RequestParam Long id) {
        log.info("delete - id: {}", id);

        boolean removed = activityInfoService.removeById(id);
        return ResponseEntity.ok(removed ? "删除成功" : "删除失败");
    }

    @PutMapping("/deactivate")
    @ApiOperation("注销活动（更新状态为'注销'）")
    public ResponseEntity<String> deactivate(@RequestParam Long id) {
        log.info("deactivate - id: {}", id);

        ActivityInfo activityInfo = activityInfoService.getById(id);
        if (activityInfo != null) {
            activityInfo.setStatus("注销");
            boolean updated = activityInfoService.updateById(activityInfo);
            return ResponseEntity.ok(updated ? "活动已注销" : "注销失败");
        } else {
            return ResponseEntity.badRequest().body("活动不存在");
        }
    }

    // 修改更新活动的接口，同时更新站点关联
    @PutMapping("/update")
    @ApiOperation("更新活动信息")
    public ResponseEntity<String> update(@RequestBody ActivityInfo activityInfo) {
        log.info("update - activityInfo: {}", activityInfo);
        try {
            boolean updated = activityInfoService.updateById(activityInfo);
            if (updated) {
                // 如果有适用范围，更新站点关联
                if (StringUtils.isNotBlank(activityInfo.getApplicableScope())) {
                    List<Long> stationIds = Arrays.stream(activityInfo.getApplicableScope().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList());
                    activityInfoService.addActivityStations(activityInfo.getId(), stationIds);
                }
                return ResponseEntity.ok("更新成功");
            } else {
                return ResponseEntity.badRequest().body("更新失败");
            }
        } catch (Exception e) {
            log.error("更新活动失败", e);
            return ResponseEntity.badRequest().body("更新失败");
        }
    }


}